<?php
/************************************************************
 * Copyright (C), 1993, Dacelve. Tech., Ltd.
 * FileName : tcp_client.php
 * Author   : Lizhijian
 * Version  : 1.0
 * Date     : 2018/1/17 14:00
 * Description   :
 * Function List :
 * History  :
 * <author>    <time>    <version >    <desc>
 * Lizhijian   2018/1/17   1.0          init
 ***********************************************************/
class tcp_client{
    public $c;
    public function __construct()
    {
        $this->c = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        $this->run();
    }

    public function run(){
        $this->connect();
        $this->receive();
        $this->error();
        $this->close();
        $this->c->connect('120.24.219.140', 9501, 0.5);
    }

    public function connect(){
        $this->c->on("connect", function($cli) {
            $data = [
                'cmd' => 'msg',
                'msg' => "通知：小明今天请假了2222\n",
                'untilTime' => 30,//持续30秒
                'userId' => 0
            ];
            $cli->send(json_encode($data));
            $data = [
                'cmd' => 'getPackList'
            ];
            $cli->send(json_encode($data));
        });
    }

    public function receive()
    {
        //注册数据接收回调
        $this->c->on("receive", function($cli, $data){
            var_dump(json_decode($data, true));
        });
    }

    public function error(){
        //注册连接失败回调
        $this->c->on("error", function($cli){
            echo "TCP服务器连接失败\n";
        });
    }

    public function close(){
        //注册连接关闭回调
        $this->c->on("close", function($cli){
            echo " TCP服务器已断开连接\n";
        });
    }
}

//$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
////注册连接成功回调
//$client->on("connect", function($cli) {
//    $data = [
//        'cmd' => 'msg',
//        'msg' => "通知：小明今天请假了2222\n",
//        'untilTime' => 30,//持续30秒
//        'userId' => 0
//    ];
//    $cli->send(json_encode($data));
//    $data = [
//        'cmd' => 'getPackList'
//    ];
//    $cli->send(json_encode($data));
//});
//
////注册数据接收回调
//$client->on("receive", function($cli, $data){
//    var_dump(json_decode($data, true));
//});
//
////注册连接失败回调
//$client->on("error", function($cli){
//    echo "TCP服务器连接失败\n";
//});
//
////注册连接关闭回调
//$client->on("close", function($cli){
//    echo " TCP服务器已断开连接\n";
//});
//
////发起连接
//$client->connect('120.24.219.140', 9501, 0.5);
//}
